import { getLayoutProps } from "@/common/layout/getProps";
import { ProForm } from "@/components/ProForm";
import { PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button, DatePicker, Descriptions,
  Divider,
  Form,
  Input, InputNumber, message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Pagination,
  type TableColumnsType,
  type TableProps
} from "antd";
import dayjs from "dayjs";
import Router from "next/router";
import type { DescriptionsItemType } from "antd/es/descriptions";
import { cloneDeep } from "lodash";
import { type Key, useState,useEffect } from "react";
import { http } from "@/utils/request";

type TableDataType = Record<string, any>;

type TableRowSelection<T> = TableProps<T>["rowSelection"];

const { confirm } = Modal;
const ActivityList = () => {
  const [form] = Form.useForm()
  const [list, setList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [editForm] = Form.useForm();
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [modalState, setModalState] = useState<'create' | 'edit' | 'detail'>('create');
  const getStateCN = (state: 'create' | 'edit' | 'detail') => {
    switch (state) {
      case 'create':
        return "新增";
      case "edit":
        return '编辑';
      case "detail":
        return "详情";
    }
  }
  const [id,setId] = useState(null);
  const [userOption,setUserOption] = useState([]);
  const [leaderIdList,setLeaderIdList] = useState([]);//领导id集合
  const [leaderNameList,setLeaderNameList] = useState([]);//领导对象集合

  const columns: TableColumnsType = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "活动名称",
      dataIndex: "activityName",
      width:140,
    },
    {
      align: "center",
      title: "活动描述",
      dataIndex: "contentDesc",
      width:180,
    },
    {
      align: "center",
      title: "评优频次",
      dataIndex: "frequency",
      width:120,
      render: (_, record) => {
        return (
          <>
            {record.frequency == "QUARTER" && <span>季度</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "活动周期",
      dataIndex: "votePersion",
      width:120,
    },
    {
      align: "center",
      title: "评优周期",
      dataIndex: "pyzq",
      width:220,
      render: (_, record) => {
        return (
          <>
            <span>{record.beginTime}——{record.endTime}</span>
          </>
        )
      }
    },
    {
      align: "center",
      title: "优秀员工人数",
      dataIndex: "personNum",
      width:120,
    },
    {
      align: "center",
      title: "创建人",
      dataIndex: "createdByName",
      width:120,
    },
    {
      align: "center",
      title: "创建时间",
      dataIndex: "createdTime",
      width:140,
    },
    {
      align: "center",
      title: "更新人",
      dataIndex: "updatedByName",
      width:120,
    },
    {
      align: "center",
      title: "更新时间",
      dataIndex: "updatedTime",
      width:140,
    },
    {
      align: "center",
      title: "投票状态",
      dataIndex: "voteStatus",
      width:120,
      fixed:'right',
      render: (_, record) => {
        return (
          <>
            {record.voteStatus == "1" && <span>开启</span>}
            {record.voteStatus == "2" && <span>关闭</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "评分状态",
      dataIndex: "ratingStatus",
      width:120,
      fixed:'right',
      render: (_, record) => {
        return (
          <>
            {record.ratingStatus == "1" && <span>开启</span>}
            {record.ratingStatus == "2" && <span>关闭</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "审核状态",
      dataIndex: "auditStatus",
      width:120,
      fixed:'right',
      render: (_, record) => {
        return (
          <>
            {record.auditStatus === "1" && <span>待提交</span>}
            {record.auditStatus === "2" && <span>审核中</span>}
            {record.auditStatus === "3" && <span>已完成</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "操作",
      width:220,
      fixed:'right',
      render: (_, record, index) => {
        return (
          <>
            <Button type={'link'} onClick={() => {
              setModalState("detail");
              setCurrentEdit(record);
              setOpen(true);
            }}>详情</Button>
            <Button type={'link'} onClick={() => {
              setModalState("edit");
              getUserOption();
              const data = cloneDeep(record);
              const [year, quarter] = data.votePersion.split('-Q');// 使用 dayjs 创建一个日期对象，并设置到季度
              data.votePersion = dayjs().year(Number(year)).quarter(Number(quarter));
              data.evaluLeader = data.evaluLeader.split(",")
              setLeaderIdList(data.evaluLeader)
              setLeaderNameList(data.evaluLeaderName.split(",").map(item=>({name:item})))
              setId(data.id)
              setCurrentEdit(data);
              setOpen(true);
            }}>编辑</Button>
            <Button type={'link'} danger onClick={() => {
              confirm({
                title: '提示?',
                content: '此操作将永久删除该数据，是否继续?',
                cancelText:'取消',
                okText:'确定',
                onOk() {
                  delData(record.id)
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}>删除</Button>
          </>
        )
      }
    }
  ]

  //删除
  const delData = async(id:number) =>{
    try {
      const res = await http.get({
        url:'/PmExcellentActivity/deleteExcellentActivity',
        params:{
          activityId:id,
        }
      })
      if(res.code==200){
        message.success('删除成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  const onSelectChange = (keys: Key[]) => {
    console.log(keys);
    setSelectedRowKeys(keys)
  }

  const rowSelection: TableRowSelection<TableDataType> = {
    selectedRowKeys,
    onChange: onSelectChange
  }
  // 开启投票
  const openVote = async()=>{
    try {
      const formData = selectedRowKeys.map(item=>({
        id:item,
        voteStatus:1
      }))
      const res = await http.post({
        url:'/PmExcellentActivity/updateExcellentActivityVote',
        data:formData
      })
      if(res.code==200){
        message.success('开启投票成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  // 开启评分
  const openScore = async()=>{
    try {
      const formData = selectedRowKeys.map(item=>({
        id:item,
        ratingStatus:1
      }))
      const res = await http.post({
        url:'/PmExcellentActivity/updateExcellentActivityVote',
        data:formData
      })
      if(res.code==200){
        message.success('开启评分成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  const handleOk = async() => {
    const values = await editForm.validateFields()
    if(values){
      //考核期间，例如：2023-Q3
      values.votePersion = dayjs(values.votePersion).format('YYYY')+ '-Q' + dayjs(dayjs(values.votePersion).format('YYYY-MM-DD')).quarter();
      const idList = leaderIdList.join(',');
      const nameList = leaderNameList.map(item => item.name).join(',');
      const formData = {
        ...values,
        frequency:'QUARTER',
        evaluLeader:idList,
        evaluLeaderName:nameList,
      }
      if(modalState=='create'){
        addSave(formData)
      }
      if(modalState=='edit'){
        editSave(formData)
      }
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmExcellentActivity/saveExcellentActivity',
        data:formData,
      })
      if(res.code == 200){
        message.success('评优活动新增成功!');
        getList();
        setOpen(false);
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmExcellentActivity/updateExcellentActivity',
        data:{id,...formData,}
      })
      if(res.code == 200){
        message.success('评优活动修改成功!');
        getList();
        setOpen(false);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const handleCancel = () => {
    setOpen(false);
    setCurrentEdit({});
    editForm.resetFields()
  }

  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmExcellentActivity/queryPmExcellentActivityList',
        params:{
          activityName:form.getFieldValue('activityName'),
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  //查询所有人员
  const getUserOption = async()=>{
    try {
      const res = await http.get({
        url:'/PmPositionPerson/pmPositionPersonAll',
        // data:{"bizUnitId":"0001101000000000182V"}//todo:因为没有部门id，暂时写死
      })
      setUserOption(res.rows.map(item=>({value:item.baseUserId,label:item.baseUserName +'-'+item.baseUserId,name:item.baseUserName})));
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  useEffect(() => {
    if (open) {
      editForm.resetFields();
      if (modalState === 'create') {
        setCurrentEdit({});
      } else {
        editForm.setFieldsValue(currentEdit);
      }
    }
  }, [open, modalState, currentEdit]);
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={getList} onReset={getList}>
        <Form.Item
          label={'活动名称'}
          name="activityName"
        >
          <Input placeholder={'请输入'}></Input>
        </Form.Item>
      </ProForm>
      <Divider className={'mb-[20px] mt-0'} />

      <Row className={'mb-[20px]'} justify={'space-between'}>
        <Space>
          <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
            setModalState("create");
            setCurrentEdit({});
            getUserOption();
            setOpen(true);
          }}>新增</Button>
        </Space>
        <Space>
          <Button type={'primary'} disabled={selectedRowKeys.length!==1} onClick={()=>{
            Router.push(`/employeeExcellentEvaluation/refereeList?activityId=${selectedRowKeys[0]}`)
          }}>推荐人清单</Button>
          <Button type={'primary'} disabled={selectedRowKeys.length!==1} onClick={()=>{
            Router.push(`/employeeExcellentEvaluation/voterConfirm?activityId=${selectedRowKeys[0]}`)
          }}>投票人清单</Button>
          <Button disabled={!selectedRowKeys.length} type={'primary'} onClick={() => {
            Modal.confirm({
                title: "提示",
                content: "此操作将开启投票，是否继续？",
                onOk(close){
                  openVote();
                  close();
                }
              })
          }}>开启投票</Button>
          <Button disabled={!selectedRowKeys.length} type={'primary'} onClick={() => {
            Modal.confirm({
                title: "提示",
                content: "此操作将开启评分，是否继续？",
                onOk(close){
                  openScore();
                  close();
                }
              })
          }}>开启评分</Button>
          <Button type={'primary'}>查看评分结果</Button>
        </Space>
      </Row>

      <Table
        scroll={{x:1800}}
        dataSource={list}
        columns={columns}
        rowSelection={rowSelection}
        rowKey={(record) => `${record.id}`}
        bordered
        pagination={false}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />

      <Modal
        open={open}
        title={`评优活动${getStateCN(modalState)}`}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            {
              modalState !== 'detail' && 
              <OkBtn />
            }
          </>
        )}
      >
        {
          modalState !== 'detail' ?
          <Form form={editForm} initialValues={currentEdit} labelCol={{span: 4}} autoComplete="off">
            <Form.Item
              label={'活动周期'}
              name={'votePersion'}
            >
              <DatePicker picker={'quarter'} className={'w-full'} onChange={(value)=>{
                console.log(dayjs(value).format('YYYY')+ '-Q' + dayjs(dayjs(value).format('YYYY-MM-DD')).quarter());
              }}/>
            </Form.Item>
            <Form.Item
              label={'活动名称'}
              name={'activityName'}
            >
              <Input placeholder={"请输入"}></Input>
            </Form.Item>
            <Form.Item
              label={'活动描述'}
              name={'contentDesc'}
            >
              <Input.TextArea placeholder={"请输入"}></Input.TextArea>
            </Form.Item>
            <Form.Item
              label={'评分领导'}
              name={'evaluLeader'}
            >
              <Select
                placeholder={'评分领导为多选项'}
                mode={'multiple'}
                options={userOption}
                showSearch
                optionFilterProp="label"
                onChange={(e,option) => {
                  setLeaderIdList(e);
                  setLeaderNameList(option);
                }}
              ></Select>
            </Form.Item>
            <Form.Item
              label={'员工人数'}
              name={'personNum'}
            >
              <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
            </Form.Item>
          </Form>
            :
          <Descriptions labelStyle={{
            width: 120
          }} column={1} items={
            cloneDeep(columns).slice(1, columns.length - 1).map(item => {
              switch (item.dataIndex) {
                case 'frequency':
                  currentEdit[item.dataIndex] = '季度'
                  break;
                case 'pyzq':
                  currentEdit[item.dataIndex] = currentEdit.beginTime+'——'+currentEdit.endTime
                  break;
                case 'voteStatus':
                  if (currentEdit[item.dataIndex]=='1') {
                    currentEdit[item.dataIndex] = '开启'
                  }else if(currentEdit[item.dataIndex]=='2'){
                    currentEdit[item.dataIndex] = '关闭'
                  }
                  break;
                case 'ratingStatus':
                  if (currentEdit[item.dataIndex]=='1') {
                    currentEdit[item.dataIndex] = '开启'
                  }else if(currentEdit[item.dataIndex]=='2'){
                    currentEdit[item.dataIndex] = '关闭'
                  }
                  break;
                case 'auditStatus':
                  if (currentEdit[item.dataIndex]=='1') {
                    currentEdit[item.dataIndex] = '待提交'
                  }else if(currentEdit[item.dataIndex]=='2'){
                    currentEdit[item.dataIndex] = '审核中'
                  }else if(currentEdit[item.dataIndex]=='3'){
                    currentEdit[item.dataIndex] = '已完成'
                  }
                  break;
              
                default:
                  break;
              }
              return {
                label: item.title,
                children: currentEdit[(item as any).dataIndex]
              }
            }) as DescriptionsItemType[]
          }></Descriptions>
        }
      </Modal>
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default ActivityList;
